package ru.compscicenter.databases.zaikina.common.model;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Word implements JSONAware, Mergeable<Word>, Cloneable {
    private final String key;
    private Integer popularity;

    public Word(String key) {
        this(key, 0);
    }

    public Word(String key, Integer popularity) {
        this.key = key;
        this.popularity = popularity;
    }

    public String getKey() {
        return key;
    }

    public Integer getPopularity() {
        return popularity;
    }

    void setPopularity(Integer popularity) {
        this.popularity = popularity;
    }

    public void addPopularity() {
        ++popularity;
    }

    public String toJSONString() {
        JSONObject obj = new JSONObject();
        obj.put("popularity", popularity);
        obj.put("key", key);
        return obj.toString();
    }

    public static Word parse(String json) {
        String key;
        Integer popularity;
        try {
            JSONObject obj = (JSONObject) JSONValue.parse(json);
            key = obj.get("key").toString();
            String value = obj.get("popularity").toString();
            popularity = Integer.parseInt(value);
        } catch (Exception ex) {
            return null;
        }
        return new Word(key, popularity);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Word) {
            Word param = (Word) obj;
            return param.popularity.equals(popularity) && param.key.equals(key);
        }
        return super.equals(obj);
    }

    public void mergeWith(Word param) {
        if (param.key == key) {
            popularity += param.popularity;
        }
    }

    public Word clone() {
        return new Word(new String(key), new Integer(popularity.intValue()));
    }
}
